package com.hksj.wlw.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hksj.base.service.DefaultDeviceService;
import com.hksj.cbm.util.DateTimeFormatUtil;
import com.hksj.cbm.util.EasyExcelUtil;
import com.hksj.wlw.mapper.WaterLeakDeviceMapper;
import com.hksj.wlw.query.WaterLeakDeviceQuery;
import com.hksj.wlw.query.WaterLeakHistoryQuery;
import com.hksj.wlw.vo.ExportWaterLeakHistoryVO;
import com.hksj.wlw.vo.WaterLeakCountVO;
import com.hksj.wlw.vo.WaterLeakDeviceHistoryVO;
import com.hksj.wlw.vo.WaterLeakDeviceVO;
import io.reactivex.rxjava3.core.Completable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WaterLeakDeviceService {

    private static final Logger log = LoggerFactory.getLogger(WaterLeakDeviceService.class);

    @Autowired
    private WaterLeakDeviceMapper waterLeakDeviceMapper;

    @Autowired
    private DefaultDeviceService defaultDeviceService;

    /**
     * 分页查询漏水设备信息
     *
     * @param query 查询条件对象，包含分页信息及查询参数
     * @return 分页结果，包含漏水设备的列表和总记录数
     */
    public IPage<WaterLeakDeviceVO> queryWaterLeakDeviceByPage(WaterLeakDeviceQuery query){
        // 根据查询条件初始化分页对象
        IPage<WaterLeakDeviceVO> page = new Page<>(query.getPageNum(), query.getPageSize());
        // 调用Mapper层的查询方法，获取分页数据列表
        List<WaterLeakDeviceVO> list = waterLeakDeviceMapper.queryWaterLeakDeviceByPage(page, query);
        // 设置查询结果列表到分页对象中
        page.setRecords(list);
        // 返回分页查询结果
        return page;
    }

    /**
     * 分页查询设备漏水的历史记录
     *
     * @param query 查询参数，包含分页信息及过滤条件
     * @return 分页数据，包含漏水设备的历史记录列表及总记录数
     */
    public IPage<WaterLeakDeviceHistoryVO> queryWaterLeakHistoryByPage(WaterLeakHistoryQuery query){
        // 创建分页对象，初始化页码和每页大小
        IPage<WaterLeakDeviceHistoryVO> page = new Page<>(query.getPageNum(), query.getPageSize());
        // 根据产品ID构建动态的属性表名
        String tableName = defaultDeviceService.getTableName(query.getProductId());

        // 对页码进行分页优化，确保数据库查询返回的是指定页码的数据
        if (query.getPageNum() > 0) {
            query.setPageNum((query.getPageNum() - 1) * query.getPageSize());
        }

        List<WaterLeakDeviceHistoryVO> list = new ArrayList<>();
        Long total = 0L;
        try {
            // 调用Mapper查询指定条件和表名下的漏水历史记录分页数据
            list = waterLeakDeviceMapper.queryWaterLeakHistoryByPage(query, tableName);
            // 查询满足条件的总记录数，用于分页显示
            total = waterLeakDeviceMapper.queryWaterLeakHistoryCount(query, tableName);
        }catch (Exception e){
            log.error("Error querying table {}: {}", tableName, e.getMessage(), e);
        }

        // 设置分页对象的记录列表和总记录数
        page.setRecords(list);
        page.setTotal(total);

        // 返回分页查询结果
        return page;
    }

    /**
     * 查询设备漏水数量统计
     *
     * @param query 查询条件，包含产品ID等信息
     * @return 返回漏水设备数量统计的列表
     */
    public List<WaterLeakCountVO> queryWaterLeakNumCount(WaterLeakHistoryQuery query){
        // 用于存储时间列表
        List<String> timeList = new ArrayList<>();

        // 根据周期类型生成相应的时间列表
        if (ObjectUtil.equals(query.getCountType(), "0")) {
            // 天周期
            timeList = DateTimeFormatUtil.getDayList(query.getStartTime(), query.getEndTime());
        } else if (ObjectUtil.equals(query.getCountType(), "1")) {
            // 月周期
            timeList = DateTimeFormatUtil.getMonthList(query.getStartTime(), query.getEndTime());
        }

        // 生成时间列表
        List<WaterLeakCountVO> list = timeList.stream().map(time -> {
                    WaterLeakCountVO waterDeviceCountVO = new WaterLeakCountVO();
                    waterDeviceCountVO.setCountTime(time);
                    return waterDeviceCountVO;
                })
                .collect(Collectors.toList());

        List<WaterLeakCountVO> countList =waterLeakDeviceMapper.queryWaterLeakNumCount(query);
        if (!CollectionUtils.isEmpty(countList)){
            Map<String, WaterLeakCountVO> map = countList.stream().collect(Collectors.toMap(WaterLeakCountVO::getCountTime, v -> v));
            list.forEach(item -> {
                if (map.containsKey(item.getCountTime())) {
                    item.setLeakCount(map.get(item.getCountTime()).getLeakCount());
                }
            });
        }

        return list;
    }

    /**
     * 导出漏水设备历史记录
     *
     * @param query       查询参数，用于分页查询漏水设备历史
     * @param response    HTTP响应对象，用于导出数据到Excel文件
     */
    public void exportWaterLeakHistory(WaterLeakHistoryQuery query, HttpServletResponse response){
        List<WaterLeakDeviceHistoryVO> list = queryWaterLeakHistoryByPage(query).getRecords();
        List<ExportWaterLeakHistoryVO> data = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)){
            int seq = 1;
            for (WaterLeakDeviceHistoryVO vo : list) {
                ExportWaterLeakHistoryVO vo1 = new ExportWaterLeakHistoryVO();
                vo1.setSeq(String.valueOf(seq++));
                vo1.setReportingTime(vo.getReportingTime());
                vo1.setLeakState(vo.getLeakState());
                data.add(vo1);
            }
        }

        //文件名称
        String fileName = new StringBuffer()
                .append("无线漏水设备历史记录")
                .append(new SimpleDateFormat("_yyyyMMddHHmmss").format(new Date()))
                .toString();

        EasyExcelUtil.exportExcelData(response, fileName, data, ExportWaterLeakHistoryVO.class);
    }

}
